package org.example.wx.config;

import io.minio.MinioClient;
import io.minio.ListBucketsArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

@Slf4j
@Configuration
public class MinioPortChecker {

    @Value("${minio.access-key:admin}")
    private String accessKey;

    @Value("${minio.secret-key:admin123}")
    private String secretKey;

    @Value("${minio.endpoint:http://39.96.219.197:9000}")
    private String primaryEndpoint;

    /**
     * 自动检测正确的MinIO API端口并创建客户端
     */
    @Bean
    @Primary
    public MinioClient autoDetectMinioClient() {
        // 首先尝试主配置的端点
        MinioClient client = tryCreateClient(primaryEndpoint);
        if (client != null) {
            log.info("MinIO client created successfully with endpoint: {}", primaryEndpoint);
            return client;
        }

        // 如果主端点失败，尝试备用端口
        String alternativeEndpoint;
        if (primaryEndpoint.contains(":9000")) {
            alternativeEndpoint = primaryEndpoint.replace(":9000", ":9001");
        } else if (primaryEndpoint.contains(":9001")) {
            alternativeEndpoint = primaryEndpoint.replace(":9001", ":9000");
        } else {
            // 如果没有指定端口，尝试标准端口
            alternativeEndpoint = primaryEndpoint + ":9001";
        }

        log.warn("Primary endpoint {} failed, trying alternative endpoint: {}", primaryEndpoint, alternativeEndpoint);
        client = tryCreateClient(alternativeEndpoint);
        if (client != null) {
            log.info("MinIO client created successfully with alternative endpoint: {}", alternativeEndpoint);
            return client;
        }

        // 都失败了，创建一个默认客户端（延迟连接）
        log.warn("无法连接到MinIO服务器。已尝试的端点：{}, {}。", primaryEndpoint, alternativeEndpoint);
        log.warn("应用将继续启动，但MinIO功能可能不可用，请检查：1) MinIO服务是否运行 2) 网络连接 3) 端口配置 4) 访问凭据");
        
        // 返回默认配置的客户端，但不测试连接
        return MinioClient.builder()
                .endpoint(primaryEndpoint)
                .credentials(accessKey, secretKey)
                .build();
    }

    private MinioClient tryCreateClient(String endpoint) {
        try {
            MinioClient client = MinioClient.builder()
                    .endpoint(endpoint)
                    .credentials(accessKey, secretKey)
                    .build();
            
            // 测试连接
            client.listBuckets(ListBucketsArgs.builder().build());
            return client;
        } catch (Exception e) {
            log.warn("Failed to connect to MinIO at endpoint {}: {}", endpoint, e.getMessage());
            return null;
        }
    }
}
